import 'package:flutter/material.dart';

class PaintWithAnimatePage extends StatefulWidget {
  const PaintWithAnimatePage({super.key});

  @override
  State<PaintWithAnimatePage> createState() => _PaintWithAnimatePageState();
}

class _PaintWithAnimatePageState extends State<PaintWithAnimatePage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _animation;
  bool _isTapped = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
    _animation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      ),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _handleTap() {
    setState(() {
      _isTapped = !_isTapped;
      if (_isTapped) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Custom Paint Example'),
      ),
      body: Center(
        child: GestureDetector(
          onTap: _handleTap,
          child: AnimatedBuilder(
            animation: _animationController,
            builder: (BuildContext context, Widget? child) {
              return CustomPaint(
                painter: _MyPainter(angle: 2 * 3.1415927 * _animation.value),
                child: Transform.rotate(
                  angle: 2 * 3.1415927 * _animation.value,
                  child: Container(
                    width: 200,
                    height: 100,
                    alignment: Alignment.center,
                    child: const Text(
                      'Hello World',
                      style: TextStyle(fontSize: 20, color: Colors.white),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      )
    );
  }
}

class _MyPainter extends CustomPainter {
  final double angle;

  _MyPainter({required this.angle});

  @override
  void paint(Canvas canvas, Size size) {
    final rect = Offset.zero & size;
    final paint = Paint()..color = Colors.blue.withOpacity(1.0);
    // ignore: unused_local_variable
    final center = rect.center;

    canvas.save();
    canvas.translate(0, 0);
    canvas.translate(size.width / 2, size.height / 2); // 平移画布
    canvas.rotate(angle); // 旋转
    canvas.translate(-size.width / 2, -size.height / 2); // 平移画布回来

    canvas.drawRect(rect, paint);
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
